package LeetCode.leetcode654;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if(nums.length == 0)
            return null;
        int index = 0;
        int max = nums[0];
        for(int i = 0; i < nums.length;i++){
            if(nums[i] > max){
                index = i;
                max = nums[i];
            }
        }
        TreeNode root = new TreeNode(max);
        int[] left = new int[index];
        int[] right = new int[nums.length - index + 1];
        for(int i = 0; i < index;i++){
            left[i] = nums[i];
        }
        for(int i = index+1,j=0;i<nums.length;i++,j++){
            right[j] = nums[i];
        }
        //递归
        root.left = constructMaximumBinaryTree(left);
        root.right = constructMaximumBinaryTree(right);
        return root;
    }
}
